package com.lsh.oms.provider.service.order.frozen;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.dubbo.rpc.protocol.rest.support.ContentType;
import com.alibaba.fastjson.JSON;
import com.lsh.base.common.json.JsonUtils;
import com.lsh.base.common.model.CommonResult;
import com.lsh.oms.api.model.order.OrderReceiptDTO;
import com.lsh.oms.api.model.other.OrderShippingDetailDto;
import com.lsh.oms.api.model.other.OrderShippingHeadDto;
import com.lsh.oms.api.model.status.UpdateStatusDto;
import com.lsh.oms.api.service.order.frozen.IOrderReceiptFrozenRestService;
import com.lsh.oms.core.constant.ReturnCode;
import com.lsh.oms.core.enums.OrderStatus;
import com.lsh.oms.core.enums.TaskStatus;
import com.lsh.oms.core.enums.TaskType;
import com.lsh.oms.core.exception.BusinessException;
import com.lsh.oms.core.exception.ExceptionStatus;
import com.lsh.oms.core.model.order.OrderHead;
import com.lsh.oms.core.model.po.OmsTask;
import com.lsh.oms.core.service.asynservice.OmsEventBus;
import com.lsh.oms.core.service.order.OrderQueryService;
import com.lsh.oms.core.service.order.frozen.OrderReceiptFrogenService;
import com.lsh.oms.core.service.po.OmsTaskService;
import com.lsh.oms.core.service.tool.ToolService;
import com.lsh.oms.core.utils.DateUtil;
import com.lsh.oms.provider.service.BaseService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.math.BigDecimal;
import java.util.List;

/**
 * Project Name: lsh-oms
 *
 * @author: miaozhuang
 * on 17/3/27.
 * 北京链商电子商务有限公司
 * Package
 * desc:订单签收RestService
 */
@Service(protocol = "rest", timeout = 30000)
@Path("order/receipt")
@Consumes({MediaType.APPLICATION_JSON})
@Produces({ContentType.APPLICATION_JSON_UTF_8})
public class OrderReceiptFrozenRestServiceImpl extends BaseService implements IOrderReceiptFrozenRestService {

    private static Logger logger = LoggerFactory.getLogger(OrderReceiptFrozenRestServiceImpl.class);

    @Autowired
    private OrderQueryService orderQueryService;

    @Autowired
    private OrderReceiptFrogenService orderReceiptFrogenService;

    @Autowired
    private OmsTaskService omsTaskService;

    @POST
    @Path("create")
    @Override
    public CommonResult<Object> create(OrderReceiptDTO receiptDTO) {
        String logSign = "logSign : " + ToolService.getLogSign();
        logger.info(logSign + ": sub-链商冻品更新订单状态（签收）入参 －－ " + (receiptDTO == null ? "" : JsonUtils.obj2Json(receiptDTO)));
        CommonResult<Object> commonResult = new CommonResult<>();
        try {
            receiptDTO.setVenderId(this.getVenderId());
            OrderHead orderHead = this.checkPara(receiptDTO, "sub");
            commonResult = orderReceiptFrogenService.createReceiptOrder(receiptDTO, orderHead, logSign);
            if (commonResult.getCode().equals(ReturnCode.REQUEST_SUCCESS)) {
                UpdateStatusDto dto = new UpdateStatusDto();
                dto.setOrderNo(orderHead.getOrderCode());
                OmsEventBus.post(dto);

                this.addNotify(orderHead.getOrderCode() + "", orderHead.getVenderId());
            }
            logger.info("sub-commonResult-receipt-" + receiptDTO.getOrderCode() + JSON.toJSONString(commonResult));
        } catch (BusinessException e) {
            commonResult.setCode(e.getCode());
            commonResult.setMessage(e.getMessage());
            logger.error("业务异常code : " + e.getCode() + ",异常信息: " + e.getMessage(), e);
        } catch (Exception e) {
            commonResult.setCode(ExceptionStatus.E3001001.getCode());
            commonResult.setMessage(ExceptionStatus.E3001001.getMessage());
            logger.error("业务异常code : " + ExceptionStatus.E3001001.getCode(), e);
        }

        return commonResult;
    }

    /**
     * @param receiptDTO
     * @param flag
     * @return
     */
    private OrderHead checkPara(OrderReceiptDTO receiptDTO, String flag) {

        if (receiptDTO == null) {
            throw new BusinessException(ReturnCode.REQUEST_PARAMS_IS_NULL, "请求参数不合法，请检验。");
        }

        if (receiptDTO.getOrderCode() == null) {
            throw new BusinessException(ReturnCode.REQUEST_PARAMS_IS_NULL, "请求参数不合法，请检验。");
        }

        if (flag.equals("sub")) {
            OrderShippingHeadDto orderShippingHeadDto = receiptDTO.getOrderShippingHeadDto();
            List<OrderShippingDetailDto> orderShippingDetailDtos = orderShippingHeadDto.getDetails();
            if (CollectionUtils.isEmpty(orderShippingDetailDtos)) {
                throw new BusinessException(ReturnCode.REQUEST_PARAMS_IS_NULL, "商品数量不能全部为0");
            }

            for (OrderShippingDetailDto orderShippingDetailDto : orderShippingDetailDtos) {
                if (orderShippingDetailDto.getQty().compareTo(BigDecimal.ZERO) <= 0) {
                    throw new BusinessException(ReturnCode.REQUEST_PARAMS_IS_NULL, "请求参数不合法，请检验。");
                }
                if (orderShippingDetailDto.getSkuId() == null) {
                    throw new BusinessException(ReturnCode.REQUEST_PARAMS_IS_NULL, "请求参数不合法，请检验。");
                }
            }
        }

        OrderHead orderHead = orderQueryService.findByCode(receiptDTO.getOrderCode(), true, false);
        if (orderHead == null) {
            throw new BusinessException(ReturnCode.FIND_ORDER_IS_NULL, "用户订单号未查询到订单");
        }

        //签收发生在发货以后
        if (orderHead.getOrderStatus().compareTo(OrderStatus.ORDER_DELIVERY.getIndex()) < 0) {
            throw new BusinessException(ReturnCode.ORDER_STATUS_ERROR, "订单状态是" + OrderStatus.getName(orderHead.getOrderStatus()) + "，请检验。");
        }

        orderHead.setUpdateTime(DateUtil.getCurrentTime());

        return orderHead;
    }

    @POST
    @Path("H5/create")
    @Override
    public CommonResult<Object> createReceiptFromShip(OrderReceiptDTO receiptDTO) {
        String logSign = "logSign : " + ToolService.getLogSign();
        logger.info(logSign + ": h5-链商冻品更新订单状态（签收）入参 －－ " + (receiptDTO == null ? "" : JsonUtils.obj2Json(receiptDTO)));
        CommonResult<Object> commonResult = new CommonResult<>();
        try {
            receiptDTO.setVenderId(this.getVenderId());
            OrderHead orderHead = this.checkPara(receiptDTO, "all");
            commonResult = orderReceiptFrogenService.createReceiptFromShip(orderHead, logSign);
            if (commonResult.getCode().equals(ReturnCode.REQUEST_SUCCESS)) {
                UpdateStatusDto dto = new UpdateStatusDto();
                dto.setOrderNo(orderHead.getOrderCode());
                OmsEventBus.post(dto);
                //添加任务
                this.addNotify(orderHead.getOrderCode() + "", orderHead.getVenderId());
            }
            logger.info("h5-commonResult-receipt-" + receiptDTO.getOrderCode() + JSON.toJSONString(commonResult));
        } catch (BusinessException e) {
            commonResult.setCode(e.getCode());
            commonResult.setMessage(e.getMessage());
            logger.error("业务异常code : " + e.getCode() + ",异常信息: " + e.getMessage(), e);
        } catch (Exception e) {
            commonResult.setCode(ExceptionStatus.E3001001.getCode());
            commonResult.setMessage(ExceptionStatus.E3001001.getMessage());
            logger.error("业务异常code : " + ExceptionStatus.E3001001.getCode(), e);
        }

        return commonResult;
    }

    /**
     * 添加任务
     *
     * @param orderCode
     */
    private void addNotify(String orderCode, Long venderId) {
        // 组合参数, 插入omsTask表中
        try {
            OmsTask filter = new OmsTask();
            filter.setRefCode(orderCode);
            filter.setTaskType(TaskType.ORDER_COUPON.getCode());
            OmsTask task = omsTaskService.getTaskOneByFilter(filter);
            // 判断omsTask是否存在记录, 存在则update, 不存在则插入
            if (task != null) {
                return;
            }

            logger.info("insert omsTask! orderCode: {}", orderCode);
            OmsTask omsTask = new OmsTask();
            omsTask.setRefCode(orderCode);
            omsTask.setTaskType(TaskType.ORDER_COUPON.getCode());
            omsTask.setTaskStatus(TaskStatus.TASK_UN_DEAL.getCode());
            omsTask.setContent(orderCode);
            omsTask.setVenderId(venderId);
            omsTaskService.add(omsTask);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @POST
    @Path("/create/confirm")
    @Override
    public CommonResult<Object> confirm(OrderReceiptDTO receiptDTO) {
        String logSign = "logSign : " + ToolService.getLogSign();
        logger.info(logSign + ": confirm黑狗（确认签收）入参 －－ " + (receiptDTO == null ? "" : JsonUtils.obj2Json(receiptDTO)));
        CommonResult<Object> commonResult = new CommonResult<>();
        try {
            OrderHead orderHead = this.checkPara(receiptDTO, logSign);
            commonResult = orderReceiptFrogenService.isCreateReceiptBill(orderHead);
            logger.info("confirm_commonResult-receipt-" + receiptDTO.getOrderCode() + JSON.toJSONString(commonResult));
        } catch (BusinessException e) {
            commonResult.setCode(e.getCode());
            commonResult.setMessage(e.getMessage());
            logger.error("业务异常code : " + e.getCode() + ",异常信息: " + e.getMessage(), e);
        } catch (Exception e) {
            commonResult.setCode(ExceptionStatus.E3001001.getCode());
            commonResult.setMessage(ExceptionStatus.E3001001.getMessage());
            logger.error("业务异常code : " + ExceptionStatus.E3001001.getCode(), e);
        }

        return commonResult;
    }
}
